<template>
  <div class="allpage">
    <div class="addman-topmenu">商品信息</div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForms"
      label-width="150px"
      class="demo-ruleForm"
      v-if="ruleForm"
    >
      <el-form-item label="商品名称：" prop="ProductName">
        <el-input style="width:45%" v-model="ruleForm.ProductName" placeholder=" 请输入商品名称"></el-input>
        <p>商品名称的字符长度不能超过60</p>
      </el-form-item>
      <el-form-item label="商品主图：" props="ProductPhoto">
        <div v-if="$route.query.type !== 'add'">
          <img :src="ruleForm.ProductPhoto[0]" style="width:148;height:148px;float:left;margin:0 10px 10px 0;" />
        </div>
        <el-upload
          ref="mainImg"
          v-model="ruleForm.ProductPhoto"
          action="http://gbtest.xiniuauto.com/api/Adm_System/UploadImgFile"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :file-list="upLoadData"
          :on-success="uploadSuccess"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品详情图：">
        <template v-if="$route.query.type !== 'add'">
          <div v-for="(item,index) in ruleForm.ProductPhoto" :key="index">
            <img :src="item" v-show="index != 0" style="width:148;height:148px;float:left;margin:0 10px 10px 0;" />
          </div>
        </template>
        
        <el-upload
          action="http://gbtest.xiniuauto.com/api/Adm_System/UploadImgFile"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="9"
          :file-list="upLoadData"
          :on-success="uploadSuccess"
          :on-error="uploadErr"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
        <div style="color:#a1a1a1">可上传多张</div>
      </el-form-item>
      <el-form-item label="视频：">
        <el-upload
          action="http://gbtest.xiniuauto.com/api/Adm_System/UploadImgFile"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :file-list="upLoadData"
          :on-success="uploadVideoSuccess"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <video width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
        <div style="color:#a1a1a1">视频时长建议9-30s，视频大小不超过30MB，建议宽高比9:16，支持的视频格式MP4</div>
      </el-form-item>
      <el-form-item label="商品规格：" prop="SoloProductModels">
        <el-input style="width:45%" v-model="ruleForm.SoloProductModels" placeholder="请输入商品规格"></el-input>
      </el-form-item>
      <el-form-item label="商品重量：" prop="Weight">
        <el-input
          style="width:45%"
          v-model="ruleForm.Weight"
          placeholder="请输入商品重量"
          maxlength="8"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          onblur="value.slice(-1) == '.'?value = value.slice(0,value.length - 1):''"
          onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
        ></el-input>
        <p>包邮请填入0，重量单位为（kg）</p>
      </el-form-item>
      <el-form-item label="单价：" class="el-input-shot">
        <!-- prop="UnitPrice" -->
        <el-input class="input" v-model="ruleForm.UnitPrice" placeholder="请输入商品价格"></el-input>
        <el-input
          class="input"
          v-model="ruleForm.UnitPriceSpecs"
          placeholder="请输入商品单价单位（/瓶）"
          style="margin-left:5px"
        ></el-input>
      </el-form-item>
      <el-form-item label="团购价：" prop="CurrentPrice" class="el-input-shot">
        <el-input
          style="width:45%"
          v-model="ruleForm.CurrentPrice"
          placeholder="请输入商品团购价格"
          maxlength="8"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          onblur="value.slice(-1) == '.'?value = value.slice(0,value.length - 1):''"
          onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
        ></el-input>
      </el-form-item>
      <el-form-item label="成本价：" prop="CostPrice" class="el-input-shot">
        <el-input
          style="width:45%"
          v-model="ruleForm.CostPrice"
          placeholder="请输入商品成本价格"
          maxlength="8"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          onblur="value.slice(-1) == '.'?value = value.slice(0,value.length - 1):''"
          onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
        ></el-input>
      </el-form-item>
      <el-form-item label="京东价：" class="el-input-shot">
        <!-- prop="JDPrice" -->
        <el-input class="input" v-model="ruleForm.JDPrice" placeholder="请输入商品京东价"></el-input>
        <el-input
          class="input"
          v-model="ruleForm.JDPriceSpecs"
          placeholder="请输入商品京东价单位（/瓶）"
          style="margin-left:5px"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品库存：" prop="Inventory">
        <el-input v-model="ruleForm.Inventory" placeholder="默认9999"></el-input>
      </el-form-item>-->
      <el-form-item label="供应商：" prop="SupplierId">
        <el-select
          ref="supplier"
          v-model="defaultSupplierName"
          style="width:45%"
          placeholder="请选择供应商"
          @change="selectTrigger"
        >
          <el-option
            v-for="supitem in options"
            :key="supitem.SupplierId"
            :label="supitem.SupplierName"
            :value="supitem.SupplierId"
            placeholder="请选择供应商"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品提成：" prop="Pro_Commission">
        <el-select v-model="ruleForm.Pro_Commission" style="width:45%" placeholder="请选择提成点项">
          <el-option
            v-for="(Comitem,Comindex) in ComOptions"
            :key="Comindex"
            :label="Comitem.label"
            :value="Comitem.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button style="margin-left:200px" @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="primary" @click="submitForm()">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  AddProducts,
  ProductsApi,
  LoadSuppliers,
  AddSalesManCommission,
  GetProducts,
} from "@/request/api";
export default {
  data() {
    const isSelect = (rule, value, callback) => {
      if (value == "") {
        return callback(new Error("请选择供应商"));
      } else {
        callback();
      }
    };
    const validateVersion = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入商品相关信息"));
      } else {
        console.log("22222");
        console.log(value);
        value += "";
        let key = value.split("");
        //  debugger
        key = key.filter((s) => {
          return s == ".";
        });
        callback();
      }
    };
    return {
      defaultSupplierName: "",
      ComOptions: [
        { value: 0.03, label: "3%" },
        { value: 0.06, label: "6%" },
        { value: 0.1, label: "10%" },
        { value: 0.15, label: "15%" },
        { value: 0.2, label: "20%" },
        { value: 0.25, label: "25%" },
        { value: 0.3, label: "30%" },
        { value: 0.35, label: "35%" },
        { value: 0.4, label: "40%" },
        { value: 0.45, label: "45%" },
        { value: 0.5, label: "50%" },
      ],
      options: [],
      msg: "",
      ruleForm: {
        Weight: 0,
        Pro_Commission: "",
        CurrentPrice: "11",
        aaa: 2,
        ProductPhoto: ['']
      },
      upLoadData: [], //图片total
      dialogImageUrl: "", //图片地址
      delivery: false,
      dialogVisible: false,
      disabled: false,
      rules: {
        ProductPhoto: [
          { require: true, message: "请上传商品主图", trigger: "blur" },
        ],
        ProductName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 5,
            message: "长度不得少于 5 个字符",
            trigger: "blur",
          },
        ],
        CostPrice: [
          { required: true, message: "请输入商品成本价格", trigger: "blur" },
        ],
        MinPrice: [
          {
            required: true,
            message: "请输入商品价格/商品单价单位",
            trigger: "blur",
          },
        ],
        SoloProductModels: [
          { required: true, message: "请输入商品规格", trigger: "blur" },
        ],
        Weight: [
          {
            required: true,
            validator: validateVersion,
            trigger: ["change", "blur"],
          },
        ],
        UnitPrice: [
          {
            required: true,
            validator: validateVersion,
            trigger: ["change", "blur"],
          },
        ],
        CostPrice: [
          {
            required: true,
            validator: validateVersion,
            trigger: ["change", "blur"],
          },
        ],
        // Inventory: [
        //   { required: true, message: "请输入商品库存", trigger: "blur" },
        // ],
        CurrentPrice: [
          {
            required: true,
            validator: validateVersion,
            trigger: ["change", "blur"],
          },
        ],
        SupplierId: [
          { required: true, message: "不能为空", trigger: ["blur", "change"] },
        ],
      },
      //监控主图数据据
      imgDate: "",
    };
  },
  methods: {
    selectTrigger(sid) {
      console.log(sid);
      this.ruleForm.SupplierId = sid;
    },
    getInfo() {
      let that = this;
      that.ruleForm.ProductNumber = this.$route.query.ProductNumber
        ? this.$route.query.ProductNumber
        : "";
      console.log(that.ruleForm.ProductNumber);
      GetProducts({
        ProductNumber: that.ruleForm.ProductNumber,
      })
        .then((res) => {
          console.log(2222222222);
          console.log(res.Data.CurrentPrice);
          console.log(res.Data.CostPrice);
          console.log(res.Data, "=============================res.Data===========================")
          //三目判断，添加商品无内容时后台返回CurrentPrice/CostPrice 为0
          res.Data.CurrentPrice === 0
            ? (res.Data.CurrentPrice = "")
            : res.Data.CurrentPrice;
          // res.Data.CurrentPrice == 0? res.Data.CurrentPrice == '':res.Data.CurrentPrice
          res.Data.CostPrice === 0
            ? (res.Data.CostPrice = "")
            : res.Data.CostPrice;
          res.Data.Pro_Commission == null
            ? (res.Data.Pro_Commission = 0.03)
            : res.Data.Pro_Commission;
          this.ruleForm = res.Data;
          //select选项
          for (let i in that.options) {
            if (that.options[i].SupplierId == res.Data.SupplierId) {
              that.defaultSupplierName = that.options[i].SupplierName;
            }
          }
          this.ruleForm.ProductPhoto = this.ruleForm.ProductPhoto.split("|");
          console.log(this.ruleForm.ProductPhoto)
          for (let j in this.ComOptions) {
            if (this.ComOptions[j].value == this.ruleForm.Pro_Commission) {
              this.ruleForm.Pro_Commission = this.ComOptions[j].label;
            }
          }
          console.log("------ruleForm----", this.ruleForm);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      var urlData = "";
      console.log("this.submitForm", this.ruleForm);
      console.log(this.ruleForm.ProductPhoto);
      for (let i in this.ruleForm.ProductPhoto) {
        if (urlData == "") {
          urlData = this.ruleForm.ProductPhoto[i];
        } else {
          urlData = urlData + "|" + this.ruleForm.ProductPhoto[i];
        }
      }
      console.log(urlData)
      //----- 供应商select验证
      if (this.defaultSupplierName === "") {
        const div = this.hint("请选择供应商");
        console.log(div);
        this.$refs.supplier.$el.querySelector("input").style.border =
          "1px solid red";
        const parent = this.$refs.supplier.$el.parentElement;
        parent.appendChild(div);
      }

      // this.ruleForm.ProductPhoto = urlData;

      //图片验证 爆红
      // if (this.ruleForm.ProductPhoto === '') {
      //   const div = this.hint('请上传商品主图')
      //   const mainImg = this.$refs.mainImg.$refs['upload-inner'].$el;
      //   const parent = mainImg.parentElement
      //   mainImg.style.border = '1px solid #F56C6C'
      //   parent.appendChild(div)

      // }
      this.ruleForm.SupplierId = this.ruleForm.SupplierId - 0;
      console.log("ruleForm", this.ruleForm);

      if (this.ruleForm.Pro_Commission === "3%") {
        this.ruleForm.Pro_Commission = 0.03;
      }
      let closeFrom = {};
      this.depClone(this.ruleForm, closeFrom);
      console.log(closeFrom);
      console.log(this.ruleForm);
      closeFrom.ProductPhoto = urlData;
      console.log(this.ruleForm.ProductPhoto);
      this.$refs.ruleForms.validate(async (vali) => {
        if (vali) {
          let that = this;
          AddProducts(closeFrom)
            .then((res) => {
              this.msg = res.message;
              this.$confirm("该条信息发布成功！", "发布成功", {});
              console.log(res);
              this.goback();
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log(this.ruleForm);
          return false;
        }
      });
    },
    //select框
    getSelect() {
      var that = this;
      LoadSuppliers()
        .then((res) => {
          this.options = res.Data;
          console.log("-----select-----", this.options);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //清除
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    uploadSuccess(response, file, fileList) {
      if (this.ruleForm.ProductPhoto == null) {
        this.ruleForm.ProductPhoto = [];
        this.ruleForm.ProductPhoto.push(
          response.OtherData + response.Data.DefaultUrl
        );
      } else {
        this.ruleForm.ProductPhoto.push(
          response.OtherData + response.Data.DefaultUrl
        );
      }
      console.log(
        "=====url====",
        response.OtherData + response.Data.DefaultUrl,
        this.ruleForm.ProductPhoto
      );
      this.imgDate = this.ruleForm.ProductPhoto;
    },
    uploadVideoSuccess(response, file, fileList) {
      if (
        response.StatusCode === 200 &&
        this.ruleForm.ProductVideo !== "" &&
        this.ruleForm.ProductVideo !== undefined &&
        this.ruleForm.ProductVideo !== null
      ) {
        this.ruleForm.ProductVideo =
          this.ruleForm.ProductVideo +
          "|" +
          response.OtherData +
          response.Data.DefaultUrl;
      } else {
        this.ruleForm.ProductVideo =
          response.OtherData + response.Data.DefaultUrl;
      }
      console.log("=====url====", response);
    },
    uploadErr(err, file, fileList) {
      console.log(err, file, fileList);
    },
    goback() {
      this.$router.back();
    },
    hint(val) {
      const div = document.createElement("div");
      div.classList.add("el-form-item__error");
      div.innerHTML = val;
      return div;
    },
    depClone(json, target) {
      var test = Object.prototype.toString;
      var nan = Object.keys(json);
      nan.forEach(
        function (value) {
          //盘断值的类型，
          //只考虑两种情况，第一种是数组，第二种是对象。
          //"[object Array]"数组，"[object Object]"，对象
          //采取Object.prototype.toString.call();
          var oldvalue = json[value];
          if (test.call(json[value]) == "[object Array]") {
            // 这是数组
            target[value] = [];
            // s
            // json[value].forEach(function(value, index) {
            //     if (test.call(value) == "[object Object]") {
            //         tar.push({});
            //         depClone(value, tar[index]);
            //         console.log(value, tar[index]);
            //     } else {
            //         tar.push(value);
            //     }

            // });
            this.depClone(oldvalue, target[value]);
          } else if (test.call(json[value]) == "[object Object]") {
            //这是对象
            target[value] = {};
            this.depClone(oldvalue, target[value]);
          } else {
            target[value] = oldvalue;
          }
          // console.log(json[value]);
        }.bind(this)
      );
    },
  },
  mounted() {
    this.$nextTick(function () {
      this.ruleForm = this.formData;
    });

    this.getSelect();
    this.getInfo();
  },
  watch: {
    formData(newVal, oldVal) {
      if (newVal) {
        this.ruleForm = { ...newVal };
        this.upLoadData = [];
        this.upLoadData.push({ url: this.ruleForm.PosterUrl });
      }
    },
    //监控select数据，变化了 ，判断是否空，有值，就得爆红去掉。文字去掉
    defaultSupplierName() {
      this.$nextTick(() => {
        if (this.defaultSupplierName !== "") {
          this.$refs.supplier.$el.querySelector("input").style.border =
            "1px solid #DCDFE6";
          const div = this.$refs.supplier.$el.nextElementSibling;
          //清除文字
          div && div.remove(div);
        }
      });
    },

    // imgDate(){
    //   this.$nextTick(()=>{
    //     if(this.ruleForm.ProductPhoto !== ''){
    //       const mainImg = this.$refs.mainImg.$refs['upload-inner'].$el;
    //       mainImg.style.border = '1px dashed #c0ccda'
    //     }
    //   })
    // }
  },
};
</script>

<style lang="less" scoped>
.addman-topmenu {
  width: 100%;
  height: 50px;
  background-color: #f8f8f8;
  line-height: 50px;
  padding-left: 10px;
  box-sizing: border-box;
  font-weight: bold;
}
.demo-ruleForm {
  margin: 20px auto;
  width: 96%;
  p {
    font-size: 12px;
    color: #a1a1a1;
  }
  .input {
    width: 45%;
  }
}
.el-form-item__content {
  flex-direction: column;
  width: 50%;
}
</style>